package iit.projects.etaxi.model.service;

import java.util.List;

import iit.projects.etaxi.model.dao.CustomerDao;
import iit.projects.etaxi.model.dao.OperatorDao;
import iit.projects.etaxi.model.dto.CustomerSCDO;
import iit.projects.etaxi.model.entity.Customer;
import iit.projects.etaxi.model.exception.DuplicateSequenceException;
import iit.projects.etaxi.model.exception.UsernameAlreadyExistsException;
import iit.projects.etaxi.util.Constants;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(readOnly = true)
public class CustomerServiceImpl implements CustomerService {

	private CustomerDao customerDao;
	private OperatorDao operatorDao;
	private SequenceGenerator sequenceGenerator;
	
	@Override
	@Transactional( readOnly=false, 
					propagation=Propagation.REQUIRES_NEW,
					rollbackFor={UsernameAlreadyExistsException.class, DuplicateSequenceException.class})
	public void saveCustomer(Customer customer) throws UsernameAlreadyExistsException, DuplicateSequenceException {
		
		if(customerDao.findByUserName(customer.getUserName()) != null){
			throw new UsernameAlreadyExistsException(new String[]{customer.getUserName()});
		}
		else if(operatorDao.findByUserName(customer.getUserName()) != null){
			throw new UsernameAlreadyExistsException(new String[]{customer.getUserName()});
		}
		
		customer.setCustomerCode(sequenceGenerator.getGeneratedCode(Constants.SequenceNames.CUSTOMER));
		customerDao.addCustomer(customer);
	}
	
	@Override
	@Transactional( readOnly=false, propagation=Propagation.REQUIRES_NEW)
	public Customer updateCustomer(Customer customer){
		return customerDao.updateCustomer(customer);
	}
	
	@Override
	public Customer findByUsername(String username){
		return customerDao.findByUserName(username);
	}
	
	@Override
	public List<Customer> findCustomers(CustomerSCDO customerSCDO) {
		return customerDao.findCustomers(customerSCDO);
	}
	
	@Override
	@Transactional( readOnly=false, propagation=Propagation.REQUIRES_NEW)
	public void deleteCustomer(Customer customer){
		customerDao.deleteCustomer(customer);
	}
	
	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}

	public void setOperatorDao(OperatorDao operatorDao) {
		this.operatorDao = operatorDao;
	}

	public void setSequenceGenerator(SequenceGenerator sequenceGenerator) {
		this.sequenceGenerator = sequenceGenerator;
	}

}
